import { useRequest } from '@umijs/hooks';
import {
  Button,
  DatePicker,
  Form,
  Input,
  Layout,
  Menu,
  message,
  Radio,
  Select,
  Table,
  Tabs,
  Tag,
  TreeSelect,
  Upload
} from 'antd';
import { CloudUploadOutlined ,RiseOutlined} from '@ant-design/icons'
import { Store } from 'rc-field-form/lib/interface';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux'
import { getOriginString, getSecretString } from '../../../../../utils/encrypt';
import { fetchRequest } from '../../../../../utils/Request';
import { url } from '../../../../../utils/url';
import XLSX from 'xlsx';
import { useSingleState } from "nice-hooks";
import moment from 'moment'
import actionTypes from '../../../actionTypes'
import Zmage from 'react-zmage'
import getImgInfo from '../../../../../utils/getImgInfo';
import cookie from 'react-cookies';
import QRCode from 'qrcode.react';
import html2Canvas from 'html2canvas';
import { useHistory } from 'react-router';
import { values } from '@antv/util';
import { useParams } from 'react-router';

import 'antd/es/modal/style';
import 'antd/es/slider/style';
import ImgCrop from 'antd-img-crop';
import exportExcel from '@/utils/exportExcel';

const { TabPane } = Tabs;

interface ValidateState {
  state: "" | "success" | "warning" | "error" | "validating" | undefined,
  help: string | undefined,

}

export default function AddStudentInformation(props: any) {
  const uploadButton = (
    <div>
      <p className="ant-upload-drag-icon">
        <CloudUploadOutlined />
      </p>
      <div className="ant-upload-text">将照片拖到此处，或<span>点击上传</span></div>
    </div>
  );
  const [urls, seturls] = useState('http://133.40.35.201:3001/#/homepage/qrcodeList')
  const { Option } = Select;
  const [userTypeList, setUserTypeList] = useState<any>([]);
  const userTypeOptions = userTypeList.map((d: any, index: number) => <Option value={d.userTypeId}
    key={index}>{d.userTypeName}</Option>);
  const [validatePhoto, setvalidatePhoto] = useState<ValidateState>({ state: undefined, help: undefined })
  const { Header, Content, Footer } = Layout;
  const [currentKey, setCurrentKey] = useState('1');
  const [isShow, setIsShow] = useState(false)
  const [excelTableData, setExcelTableData] = useState<any[]>([]);
  const [batchAddDeptId, setBatchAddDeptId] = useState<any>('');
  const [batchAddUserTypeId, setBatchAddUserTypeId] = useState<any>('');
  const [batchAddList, setBatchAddList] = useState<any[]>([]);
  const [excelFlag, setExcelFlag] = useState<boolean>(false);
  const [state, setState] = useSingleState({ fileStoreName: "" })
  const [photoInfo, setphotoInfo] = useState({
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: []
  })
  const errorcolumns = [{ title: "错误说明", dataIndex: 'errorTitle', key: 'errorTitle' }]
  const columns = [
    {
      title: "姓名",
      dataIndex: 'studentName',
      key: 'studentName',
      render: (text: string) => text === "" ? <Tag color={'#f50206'}>姓名未填</Tag> : text
    },
    {
      title: "性别", dataIndex: 'sex', key: 'sex', render: (text: string) => {
        if (text === "") {
          return <Tag color={'#f50206'}>性别未填</Tag>;
        }
        if (text !== "男" && text !== "女") {
          return <Tag color={'#f50206'}>{text}:性别异常</Tag>;
        }
        return text;
      }
    },
    {
      title: "联系电话", dataIndex: 'phone', key: 'phone', render: (text: string) => {
        if (text === "") {
          return <Tag color={'#f50206'}>联系电话未填</Tag>;
        }
        if (!/^1[3456789]\d{9}$/.test(text)) {
          return <Tag color={'#f50206'}>{text}:格式异常</Tag>;
        }
        return text;
      }
    }, {
      title: "监护人电话", dataIndex: 'guardianPhone', key: 'guardianPhone', render: (text: string) => {
        if (text === "") {
          return <Tag color={'#f50206'}>联系电话未填</Tag>;
        }
        if (!/^1[3456789]\d{9}$/.test(text)) {
          return <Tag color={'#f50206'}>{text}:格式异常</Tag>;
        }
        return text;
      }
    },
    {
      title: "证件号码", dataIndex: 'credentialsNum', key: 'credentialsNum', render: (text: string) => {
        if (text === "") {
          return <Tag color={'#f50206'}>证件号码未填</Tag>;
        }
        if (!/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(text)) {
          return <Tag color={'#f50206'}>{text}:格式异常</Tag>;
        }
        return text;
      }
    },
    {
      title: "智能学生证卡号",
      dataIndex: "wisdomCardImei",
      key: 'wisdomCardImei'
    },
    {
      title: "学号", dataIndex: 'studentId', key: 'studentId', render: (text: string) => {
        if (text === "") {
          return <Tag color={'#f50206'}>学号未填</Tag>;
        }
        return text;
      }
    },
    {
      title: "入学时间", dataIndex: 'startSchoolDate', key: 'startSchoolDate', render: (text: string) => {
        if (text === "") {
          return <Tag color={'#f50206'}>入学未填</Tag>;
        }
        return text;
      }
    },
    {
      title: "毕业时间", dataIndex: 'graduationDate', key: 'graduationDate', render: (text: string) => {
        if (text === "") {
          return <Tag color={'#f50206'}>毕业未填</Tag>;
        }
        return text;
      }
    }
  ];


  //获取redux中的数据
  const myData = useSelector((state: any) => {

    const data = state.deptManage.deptData
    disableSelect(data)
    return {
      deptData: data,
    }
  });

  //获取redux中的数据
  const errorData = useSelector((state: any) => {

    return state.entranceManage.errorstudentData

  });

  useEffect(() => {
    getUserTypeRequest();
  }, []);

  // console.log("错误提示")
  // console.log(errorData.data)
  function handleExcelFile(e: any) {
    if (e.target.files[0] === null || e.target.files[0] === undefined) {
      return false;
    }
    let f = e.target.files[0];
    let reader = new FileReader();  // 使用 FileReader 读取数据
    reader.onload = function (e) {  // 数据读取完成后的回调函数
      try {
        // @ts-ignore
        let workbook = XLSX.read(e.target.result, { type: 'binary' })
        let firstSheetName = workbook.SheetNames[0];  // 获取第一个 sheet 的名字
        let worksheet = workbook.Sheets[firstSheetName];  // 获取第一个 sheet 的内容
        let res = XLSX.utils.sheet_to_json(worksheet);  // 使用 utils 里的方法转换内容为便于使用的数组
        console.log('res', res)
        const list: any[] = [];
        const addList: any[] = [];
        res.map((item: any) => {
          list.push({
            rowNum: item.__rowNum__,
            studentName: (item.姓名 === "" || item.姓名 === undefined) ? "" : item.姓名.trim(),
            sex: (item.性别 === "" || item.性别 === undefined) ? "" : item.性别.trim(),
            phone: (item.联系电话 === "" || item.联系电话 === undefined) ? "" : item.联系电话.trim(),
            guardianPhone: (item.监护人电话 === "" || item.监护人电话 === undefined) ? "" : item.监护人电话.trim(),
            credentialsNum: (item.证件号码 === "" || item.证件号码 === undefined) ? "" : item.证件号码.trim(),
            studentId: (item.学号 === "" || item.学号 === undefined) ? "" : item.学号.trim(),
            wisdomCardImei: (item.智能学生证卡号 === "" || item.智能学生证卡号 === undefined) ? "" : item.智能学生证卡号.trim(),
            startSchoolDate: (item.入学时间 === "" || item.入学时间 === undefined) ? "" : item.入学时间.trim(),
            graduationDate: (item.毕业时间 === "" || item.毕业时间 === undefined) ? "" : item.毕业时间.trim(),
          })

          addList.push({
            studentName: (item.姓名 === "" || item.姓名 === undefined) ? "" : item.姓名.trim(),
            sex: (item.性别 === "" || item.性别 === undefined) ? "" : item.性别.trim(),
            phone: (item.联系电话 === "" || item.联系电话 === undefined) ? "" : item.联系电话.trim().toString(),
            guardianPhone: (item.监护人电话 === "" || item.监护人电话 === undefined) ? "" : item.监护人电话.trim(),
            credentialsNum: (item.证件号码 === "" || item.证件号码 === undefined) ? "" : item.证件号码.trim().toString(),
            studentId: (item.学号 === "" || item.学号 === undefined) ? "" : item.学号.trim(),
            wisdomCardImei: (item.智能学生证卡号 === "" || item.智能学生证卡号 === undefined) ? "" : item.智能学生证卡号.trim(),
            startSchoolDate: (item.入学时间 === "" || item.入学时间 === undefined) ? "" : item.入学时间.trim(),
            graduationDate: (item.毕业时间 === "" || item.毕业时间 === undefined) ? "" : item.毕业时间.trim(),
          })
        });
        // console.log("list数据",list);
        setExcelTableData(list);
        excelDataCheck(addList);
      } catch (e) {
        console.log(e);
        message.error("数据异常！");
      }
    };
    reader.readAsBinaryString(f);  // 读取数据
  }

  function excelDataCheck(data: any) {
    let falseFlag = true;
    let repeaterror = "";
    for (let i = 0; i < data.length; i++) {
      if (data[i].studentName === "" || data[i].sex === "" || data[i].phone === "" || data[i].credentialsNum === ""
        || data[i].studentId === "" || data[i].start_date === "" || data[i].end_date === "") {
        falseFlag = false;
      } else if (data[i].sex !== "男" && data[i].sex !== "女") {
        falseFlag = false;
      } else if (!/^1[3456789]\d{9}$/.test(data[i].phone)) {
        falseFlag = false;
      } else if (!/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(data[i].credentialsNum)) {
        falseFlag = false;
      }
      let temp = data[i];
      for (let j = i + 1; j < data.length; j++) {
        if (temp.phone === data[j].phone) {
          repeaterror = "电话号码" + temp.phone + "有多条数据";
          falseFlag = false;
        }
        if (temp.credentialsNum === data[j].credentialsNum) {
          repeaterror = repeaterror + "   " + "身份证号码" + temp.credentialsNum + "有多条数据";
          falseFlag = false;
        }
        if (temp.studentId === data[j].studentId) {
          repeaterror = repeaterror + "   " + "学号" + temp.studentId + "有多条数据";
          falseFlag = false;
        }
      }
      data[i].phone = getSecretString(data[i].phone);
      data[i].guardianPhone = getSecretString(data[i].guardianPhone);
      data[i].photo = "";
      data[i].studentId = getSecretString(data[i].studentId);
      data[i].credentialsNum = getSecretString(data[i].credentialsNum);
      data[i].startSchoolDate = moment(data[i].startSchoolDate).format('YYYY-MM-DD');
      data[i].graduationDate = moment(data[i].graduationDate).format('YYYY-MM-DD');
    }


    if (falseFlag) {
      setBatchAddList(data);
      setExcelFlag(true);
    } else {
      message.error(repeaterror);
      setExcelFlag(false);
    }
  }


  //递归修改item的key
  function disableSelect(arr: any[],) {
    arr.map(item => {
      delete item.disabled
      item.key = item.deptID
      item.value = item.deptID
      if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
        return;
      } else {
        item.selectable = false
        disableSelect(item.children)
      }
    })
  }

  const [form] = Form.useForm();

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 14 },
  };
  const dispatch = useDispatch()
  const tailLayout = {
    wrapperCol: { offset: 5, span: 14 },
  };
  //是否通过Img检测
  const [imgFlag, setImgFlag] = useState(false);
  const [ExportData , setExportData] = useState([])

  function onFinish(value: Store) {


    if (imgFlag) {
      message.error('人脸识别未通过')
      return
    }


    const data = {
      studentName: value.studentName,
      phone: getSecretString(value.phone),
      guardianPhone: getSecretString(value.guardianPhone == undefined ? "" : value.guardianPhone),
      credentialsNum: getSecretString(value.credentialsNum),
      studentId: getSecretString(value.studentId),
      sex: value.sex,
      wisdomCardImei: value.wisdomCardImei,
      startSchoolDate: moment(value.start_date).format('YYYY-MM-DD'),
      graduationDate: moment(value.end_date).format('YYYY-MM-DD'),
      photo: state.fileStoreName
    };

    console.log(data)
    const params = {
      deptId: value.deptId,
      userTypeId: value.userType,
      listUserDept: [data]
    };

    // console.log(params)

    addNewStaffOne.run(params)
  }

  function menuClick(e: any) {
    setCurrentKey(e.key);
  }

  function batchTreeOnchange(value: any) {
    setBatchAddDeptId(value)
  }

  function UserTypeOnChange(value: any) {
    setBatchAddUserTypeId(value);
    // console.log(value)
  }

  function batchAddClick() {
    if (batchAddDeptId === "") {
      message.error("请选择部门！");
      return;
    }
    if (!excelFlag) {
      message.error("excel数据异常，请修改！");
      return;
    }
    const param = {
      deptId: batchAddDeptId,
      userTypeId: batchAddUserTypeId,
      listUserDept: batchAddList
    };
    // console.log(param)
    addNewStaff.run(param);
  }

  async function addNewStaffOneRequest(params: any) {
    try {
      const json = await fetchRequest(url.ADD_STUDENT_INFORMATION, params);
      if (json.success) {
        message.destroy();
        message.success("新增成功!");
        props.addSuccess();
      } else {
        message.destroy();
        message.error("新增失败！" + json.info.errorList[0].errorTitle);

      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  async function getUserTypeRequest() {
    let params = {
      teacherTypeId: '',
      teacherTypeName: ''
    }
    try {
      const json = await fetchRequest(url.GET_USER_TYPE, params);
      if (json.success) {
        setUserTypeList(json.data);
        // form.setFieldsValue({userType:json.data[0].userTypeId})
      } else {
        message.error(json.error)
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const getUserType = useRequest(getUserTypeRequest, {
    manual: true,
    loadingDelay: 200
  });


  async function addNewStaffRequest(params: any) {
    try {
      const json = await fetchRequest(url.ADD_STUDENT_INFORMATION, params);
      setExportData(json.info.exportList)
      if (json.success && json.info.falseCount === 0) {
        message.destroy();
        message.success("新增成功!");
        props.addSuccess();
      } else {
        if (json.info.falseCount != 0) {
          message.destroy();
          message.error("部分导入成功，导入成功" + json.info.successCount + "条，失败" + json.info.falseCount + "条！详情请看错误提示！！！");
          dispatch({
            type: actionTypes.GET_STUDENT_ERROR_LIST,
            payload: {
              data: json.info.errorList, count: json.info.falseCount
            }
          })
        } else {
          message.destroy();
          message.error(json.info.error + "，详情请看错误提示！！！");
          dispatch({
            type: actionTypes.GET_STUDENT_ERROR_LIST,
            payload: {
              data: json.info.errorList, count: json.info.falseCount
            }
          })
        }

      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const addNewStaff = useRequest(addNewStaffRequest, {
    manual: true,
    loadingDelay: 200
  })
  const handleExport = () =>{
     const data = ExportData.map((item: any) => {
      const tempItem = {}
      tempItem['姓名'] = item.studentName
      tempItem['性别'] = item?.sex
      tempItem['联系电话'] = getOriginString(item.phone)
      tempItem['监护人电话'] = getOriginString(item.guardianPhone)
      tempItem['证件号码'] = getOriginString(item.credentialsNum)
      tempItem['智能学生证卡号'] = item.wisdomCardImei
      tempItem['学号'] = getOriginString(item.studentId)
      tempItem['入学时间'] = item.startSchoolDate
      tempItem['毕业时间'] = item.graduationDate 
      tempItem['结果'] = item.errorTitle 
      return tempItem
  })
  exportExcel(data, '学生信息批量导入模板.xlsx')
     
  }
  const addNewStaffOne = useRequest(addNewStaffOneRequest, {
    manual: true,
    loadingDelay: 200
  })

  const getSrcFromFile = (file: any) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(file.originFileObj);
      reader.onload = () => resolve(reader.result);
    });
  };

  async function onFilePreview(value: any) {
    const src = value.url || (await getSrcFromFile(value));
    Zmage.browsing({ src: src })
  }
  function normFile({ fileList }: any) {
    if (fileList.length > 0 && fileList[0].status === "done") {
      if (fileList[0].response.success) {
        setState({ fileStoreName: fileList[0].response.files[0].fileStoreName })
        const myFile = [];
        myFile[0] = {
          ...fileList[0],
          url: url.GET_PERSON_FACE_URL +
            "accessToken=" +
            getImgInfo(fileList[0].response.files[0].fileStoreName)
        }
        return myFile
      } else {
        const myFile = [];
        myFile[0] = {
          ...fileList[0],
          status: "error"
        }
        return myFile;
      }
    } else
      return fileList
  };
  //当上传的文件变化的时候
  function onFileChange(info: any) {
    if (info.file.status === 'done') {
      const params = {
        storeName: state.fileStoreName
      }
      checkUserPhoto(params);
    }
    setphotoInfo({ ...photoInfo, fileList: info.fileList })
  }

  //人脸检测接口
  async function checkUserPhoto(params: any) {
    try {
      setvalidatePhoto({ state: 'validating', help: "" })
      const json = await fetchRequest(url.CHECK_FACE_URL, params);
      if (json.success) {
        setvalidatePhoto({ state: "success", help: json.result })
        return Promise.resolve();
      } else {
        setImgFlag(true)
        setvalidatePhoto({ state: "error", help: json.result });
        return Promise.reject(json.result)
      }
    } catch (error: any) {
      setvalidatePhoto({ state: "error", help: "照片验证失败" })
      return Promise.reject("照片验证失败")
    }
  }


  const removePicture = () => {
    setvalidatePhoto({ state: '', help: "" })
    setState({
      fileStoreName: ''
    }, () => {
    })
    setImgFlag(false)
  }
  const [treeName, setTreeName] = useState('')
  const TreeChange = (value: any, label: any) => {
    setTreeName(label[0])
    seturls(
      `https://zhsq.sctel.com.cn/wisdomCollegeView/#/qrcodeList/${cookie.load("collegeToken")}/${value}/${encodeURIComponent(label[0])}`
      // `http://133.40.35.201:3000/#/qrcodeList/${cookie.load("collegeToken")}/${value}/${encodeURIComponent(label[0])}`
    )
  }
  var [canva, setcanva] = useState<string>('')
  const getChonsenPic = (e: any) => {
    if (!treeName && treeName.length == 0) {
      message.error('请选择组织机构')
      return
    }
    setIsShow(true)
   fetchRequest(url.GET_TOKEN,{}).then(()=>{

   })
    // setCurrentKey(e)
    html2Canvas(document.querySelector('#Div')!, {
    }).then((canvas) => {
      let url = canvas.toDataURL()
      setcanva(url)
    })
  }

  return (
    <div>
      <div id='Div' style={{ height: '20px', position: 'absolute', top: '-500px', color: 'red', fontSize: '12px', backgroundColor: "rgba(0,0,0,0)" }}>{treeName}</div>
      {
        isShow ? <div className="site-layout-background" style={{ minHeight: 380 }}>
          <QRCode value={urls} size={200} imageSettings={{
            src: canva, height: 20,
            width: 80, excavate: true
          }} />
        </div> : <>

          <Menu theme={"light"} onClick={menuClick} mode="horizontal" defaultSelectedKeys={['1']}>
            <Menu.Item key="1">单个新增</Menu.Item>
            <Menu.Item key="2">批量新增</Menu.Item>
          </Menu>
          <Content className="site-layout" style={{ padding: '0 50px', marginTop: 64 }}>
            <div hidden={currentKey === '2'} className="site-layout-background" style={{ minHeight: 380 }}>
              <Form form={form} {...layout} onFinish={onFinish}>
                <Form.Item label="姓名" name="studentName" rules={[{
                  required: true, message: '必须要输入用户名'
                },
                {
                  max: 20,
                  message: '姓名长度过长'
                }
                  ,
                {
                  pattern: /^[\u4e00-\u9fa5]|[a-zA-Z]$/,
                  message: '姓名不符合规范'
                }
                ]}>
                  <Input placeholder="请填写姓名" />
                </Form.Item>

                <Form.Item label="性别" name="sex" rules={[{ required: true, message: '必须选择性别' }]}>
                  <div>
                    <Radio.Group>
                      <Radio value={"男"} key={"1"}>男</Radio>
                      <Radio value={"女"} key={"2"}>女</Radio>
                    </Radio.Group>
                  </div>
                </Form.Item>

                <Form.Item label="人员类型" name="userType" rules={[{ required: true, message: "必须要选择人员类型!" }]}>
                  <Select
                    style={{ width: '100%' }}
                    placeholder="请选择人员类型"
                  // onChange={typeOnChange}
                  >
                    {userTypeOptions}
                  </Select>
                </Form.Item>

                <Form.Item label="联系电话" name="phone" rules={[{ required: true, message: '必须要输入手机号码' }, {
                  pattern: /^1[3456789]\d{9}$/,
                  message: '手机号码格式错误！'
                }]}>
                  <Input placeholder="请输入手机号码" />
                </Form.Item>

                <Form.Item label="监护人电话" name="guardianPhone"
                  rules={[{ required: false }, { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' }]}>
                  <Input placeholder="请输入监护人电话" />
                </Form.Item>
                <Form.Item label="智能学生证卡号" name="wisdomCardImei">
                  <Input placeholder="请输入智能学生证卡号" />
                </Form.Item>
                <Form.Item label="学号" name="studentId" rules={[{ required: true, message: '必须要输入学号' }]}>
                  <Input placeholder="请输入学号" />
                </Form.Item>

                <Form.Item label="身份证号" name="credentialsNum" rules={[{
                  required: true,
                  message: '必须要输入身份证号码'
                }, {
                  pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                  message: '身份证格式错误！'
                }]}>
                  <Input placeholder="请输入身份证号码" />
                </Form.Item>

                <Form.Item label="入学时间" name="start_date" rules={[{ required: true, message: '必须要选择时间' }]}>
                  <DatePicker />
                </Form.Item>

                <Form.Item label="毕业时间" name="end_date" rules={[{ required: true, message: '必须要选择时间' }]}>
                  <DatePicker />
                </Form.Item>
                <Form.Item
                  validateStatus={validatePhoto.state}
                  help={validatePhoto.help}
                  hasFeedback
                  valuePropName="fileList"
                  getValueFromEvent={normFile} label="人脸照片" name="facePic">
                  {/* <ImgCrop  grid rotate> */}
                  <Upload listType="picture-card"
                    action={url.UPLOAD_PERSON_URL}
                    //@ts-ignore
                    // fileList={photoInfo.fileList}
                    showUploadList={{
                      showPreviewIcon: true,
                      // showRemoveIcon: canChangePic ? true : false,
                      showDownloadIcon: true
                    }}
                    onRemove={removePicture}
                    onPreview={onFilePreview}
                    onChange={onFileChange}
                    headers={{ token: cookie.load("collegeToken") }}
                    accept=".png,.svg,.jpg,.jpeg,.gif">
                    {photoInfo.fileList.length >= 1 ? null : uploadButton}
                  </Upload>
                  {/* </ImgCrop> */}
                </Form.Item>


                <Form.Item className="form-control-item" name="deptId" label="组织机构"
                  rules={[{ required: true, message: '必须要选择组织机构' }]}>
                  <TreeSelect className="form-item"
                    style={{ width: '100%' }}
                    treeData={myData.deptData}
                    showSearch
                    onChange={TreeChange}
                    treeNodeFilterProp={'title'}

                    fieldNames={{
                      label: 'title', value: 'value', children: 'children',

                    }}
                    // treeData={treeData}
                    placeholder="请选择组织机构"></TreeSelect>
                </Form.Item>

                <Form.Item {...tailLayout}>
                  <Button type="primary" htmlType="submit">提交</Button>
                  <Button type="primary" onClick={() => { getChonsenPic('3') }} style={{ marginLeft: '10px' }}>生成二维码</Button>
                </Form.Item>
              </Form>
            </div>
            <div hidden={currentKey === '1'} className="site-layout-background" style={{ minHeight: 380 }}>
              <div style={{ display: "flex", flexDirection: "row", alignItems: "center", padding: 20 }}>
                <span>导入模板：</span>
                <a href={require('../../../../../excel/学生信息批量导入模板.xlsx')} download
                  style={{ color: '#1153ff', fontWeight: 500 }}>模板下载</a>
              </div>
              <div style={{ display: "flex", flexDirection: "row", alignItems: "center", padding: 20 }}>
                <span>组织机构：</span>
                <TreeSelect id="batch-tree" className="form-item" onChange={batchTreeOnchange}
                  // treeData={treeData}
                  treeData={myData.deptData}
                  treeDefaultExpandAll placeholder="请选择组织机构" />
              </div>
              <div style={{ display: "flex", flexDirection: "row", alignItems: "center", padding: 20 }}>
                <span>人员类型：</span>
                <Select
                  style={{ width: '30%' }}
                  placeholder="请选择人员类型"
                  onChange={UserTypeOnChange}
                >
                  {userTypeOptions}
                </Select>
              </div>
              <div style={{ display: "flex", flexDirection: "row", alignItems: "center", padding: 20 }}>
                <span>上传文件：</span>
                <input type="file" accept=".xlsx,.xls" onChange={handleExcelFile} />
              </div>
              <div style={{ padding: 20 }}>
                <span>数据预览：</span>
                <Table style={{ marginTop: 20 }}
                  pagination={{
                    hideOnSinglePage: true,
                    simple: true,
                    pageSize: 10,
                    total: excelTableData.length
                  }}
                  rowKey={(record: any) => record.rowNum} columns={columns} dataSource={excelTableData} />
              </div>
              <div style={{ padding: 20 }}>
                <Button type="primary" htmlType="submit" onClick={batchAddClick}
                  loading={addNewStaff.loading}>提交</Button>
                   <Button  type={'primary'}
            style={{
              margin: '0 10px'
            }}
            onClick={handleExport}
          >导出</Button>
              </div>
              <div style={{ padding: 20 }}>
                <span>错误提示：</span>
                <Table style={{ marginTop: 20 }}
                  pagination={{
                    hideOnSinglePage: true, simple: true, pageSize: 10,
                    total: errorData.count
                  }}
                  rowKey={(record: any) => record.rowNum} columns={errorcolumns}
                  dataSource={errorData.data} />
              </div>

            </div>

          </Content></>
      }
    </div>
  )

}
function compressImg(file: any) {
  throw new Error('Function not implemented.');
}

